<template>
  <div class="user-management">
    <div class="header">
      <h2>用户管理</h2>
      <p>管理系统中的所有用户信息</p>
    </div>
    
    <!-- 搜索和操作栏 -->
    <div class="toolbar">
      <el-card class="search-card">
        <el-row :gutter="20" align="middle">
          <el-col :span="16">
            <div class="search-fields">
              <el-input
                v-model="searchForm.name"
                placeholder="请输入姓名"
                style="width: 180px; margin-right: 10px"
                clearable
                prefix-icon="el-icon-search"
              />
              <el-input
                v-model="searchForm.username"
                placeholder="请输入用户名"
                style="width: 180px; margin-right: 10px"
                clearable
                prefix-icon="el-icon-user"
              />
              <el-select
                v-model="searchForm.status"
                placeholder="请选择状态"
                style="width: 120px; margin-right: 10px"
                clearable
              >
                <el-option label="启用" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
              <el-button type="primary" @click="searchUsers">
                <i class="el-icon-search"></i>
                搜索
              </el-button>
              <el-button @click="resetSearch">
                <i class="el-icon-refresh"></i>
                重置
              </el-button>
            </div>
          </el-col>
          <el-col :span="8" style="text-align: right">
            <el-button type="primary" @click="showAddUserDialog">
              <i class="el-icon-plus"></i>
              新增用户
            </el-button>
          </el-col>
        </el-row>
      </el-card>
    </div>

    <!-- 用户列表 -->
    <div class="user-table">
      <el-card>
        <el-table
          :data="userList"
          border
          style="width: 100%"
          v-loading="loading"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        >
          <el-table-column prop="id" label="ID" width="80" align="center" />
          <el-table-column label="头像" width="80" align="center">
            <template #default="scope">
              <img 
                v-if="scope.row.avatar" 
                :src="`http://localhost:8080/api/users/avatar/${scope.row.id}?t=${Date.now()}`" 
                class="user-avatar"
                @error="handleAvatarError(scope.row)"
              />
              <el-avatar v-else :size="30">{{ scope.row.name ? scope.row.name.charAt(0) : scope.row.username.charAt(0) }}</el-avatar>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="用户名" width="150" />
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="phone" label="手机号" width="150" />
          <el-table-column prop="department" label="部门" width="150" />
          <el-table-column prop="role" label="角色" width="120">
            <template #default="scope">
              <span v-if="getRoleDescription(scope.row.role)">
                {{ getRoleDescription(scope.row.role) }}
              </span>
              <span v-else>
                {{ scope.row.role }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                {{ scope.row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" align="center">
            <template #default="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right" align="center">
            <template #default="scope">
              <el-button size="small" @click="showEditUserDialog(scope.row)">
                <i class="el-icon-edit"></i>
                编辑
              </el-button>
              <el-button 
                size="small" 
                :type="scope.row.status === 1 ? 'warning' : 'success'"
                @click="toggleUserStatus(scope.row)"
              >
                {{ scope.row.status === 1 ? '禁用' : '启用' }}
              </el-button>
              <el-button size="small" type="danger" @click="deleteUser(scope.row)">
                <i class="el-icon-delete"></i>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
      />
    </div>

    <!-- 用户编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="handleDialogClose"
      :modal-append-to-body="false"
    >
      <el-form
        :model="userForm"
        :rules="userFormRules"
        ref="userFormRef"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="isEdit" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-input v-model="userForm.department" placeholder="请输入部门" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="userForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
        <el-form-item v-if="!isEdit" label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item v-if="!isEdit" label="确认密码" prop="confirmPassword">
          <el-input v-model="userForm.confirmPassword" type="password" placeholder="请确认密码" show-password />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option 
              v-for="role in roles" 
              :key="role.id" 
              :label="role.roleDescription || role.roleName" 
              :value="role.roleName" 
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUserForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '../../utils/request'
import { useRouter } from 'vue-router'

// 定义响应式数据
const userList = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const router = useRouter()

// 角色列表
const roles = ref([])

// 搜索表单
const searchForm = reactive({
  name: '',
  username: '',
  status: null as number | null
})

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 用户表单
const userForm = reactive({
  id: null as number | null,
  username: '',
  name: '',
  phone: '',
  department: '',
  status: 1,
  role: 'STUDENT',
  password: '',
  confirmPassword: ''
})

// 表单验证规则
const userFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== userForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 表单引用
const userFormRef = ref()

// 处理头像加载错误
const handleAvatarError = (user: any) => {
  // 当头像加载失败时，使用默认头像
  console.log(`Avatar load failed for user ${user.id}, using default avatar`)
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true
  try {
    const response = await request.get('/api/users', {
      params: {
        page: pagination.currentPage - 1, // Spring Data JPA页面从0开始，前端从1开始
        size: pagination.pageSize,
        name: searchForm.name,
        username: searchForm.username,
        status: searchForm.status
      }
    })
    
    userList.value = response.data.content
    pagination.total = response.data.totalElements
  } catch (error: any) {
    if (error.response && error.response.status === 403) {
      ElMessage.error('权限不足，请重新登录')
      // 清除本地存储并跳转到登录页
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      router.push('/login')
    } else {
      ElMessage.error('获取用户列表失败')
    }
  } finally {
    loading.value = false
  }
}

// 搜索用户
const searchUsers = () => {
  pagination.currentPage = 1
  fetchUsers()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.username = ''
  searchForm.status = null
  pagination.currentPage = 1
  fetchUsers()
}

// 处理分页变化
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  pagination.currentPage = 1 // 重置到第一页
  fetchUsers()
}

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  fetchUsers()
}

// 显示添加用户对话框
const showAddUserDialog = () => {
  dialogTitle.value = '新增用户'
  isEdit.value = false
  dialogVisible.value = true
  // 重置表单
  Object.assign(userForm, {
    id: null,
    username: '',
    name: '',
    phone: '',
    department: '',
    status: 1,
    role: 'STUDENT',
    password: '',
    confirmPassword: ''
  })
}

// 显示编辑用户对话框
const showEditUserDialog = (user: any) => {
  dialogTitle.value = '编辑用户'
  isEdit.value = true
  dialogVisible.value = true
  // 填充表单数据
  Object.assign(userForm, {
    id: user.id,
    username: user.username,
    name: user.name,
    phone: user.phone,
    department: user.department,
    status: user.status,
    role: user.role,
    password: '',
    confirmPassword: ''
  })
}

// 提交用户表单
const submitUserForm = async () => {
  if (!userFormRef.value) return
  
  await userFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        if (isEdit.value) {
          // 编辑用户
          await request.put(`/api/users/${userForm.id}`, {
            name: userForm.name,
            phone: userForm.phone,
            department: userForm.department,
            status: userForm.status,
            role: userForm.role
          })
          ElMessage.success('用户更新成功')
        } else {
          // 新增用户
          await request.post('/api/users', {
            username: userForm.username,
            name: userForm.name,
            phone: userForm.phone,
            department: userForm.department,
            status: userForm.status,
            password: userForm.password,
            role: userForm.role
          })
          ElMessage.success('用户创建成功')
        }
        
        dialogVisible.value = false
        fetchUsers()
      } catch (error: any) {
        if (error.response && error.response.status === 403) {
          ElMessage.error('权限不足，请重新登录')
          // 清除本地存储并跳转到登录页
          localStorage.removeItem('token')
          localStorage.removeItem('userInfo')
          router.push('/login')
        } else {
          ElMessage.error(isEdit.value ? '用户更新失败' : '用户创建失败')
        }
      }
    }
  })
}

// 处理对话框关闭
const handleDialogClose = () => {
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
}

// 切换用户状态
const toggleUserStatus = async (user: any) => {
  try {
    await request.put(`/api/users/${user.id}/status`, {
      status: user.status === 1 ? 0 : 1
    })
    ElMessage.success('状态更新成功')
    fetchUsers()
  } catch (error: any) {
    if (error.response && error.response.status === 403) {
      ElMessage.error('权限不足，请重新登录')
      // 清除本地存储并跳转到登录页
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      router.push('/login')
    } else {
      ElMessage.error('状态更新失败')
    }
  }
}

// 删除用户
const deleteUser = (user: any) => {
  ElMessageBox.confirm(
    `确定要删除用户 "${user.name}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await request.delete(`/api/users/${user.id}`)
      ElMessage.success('用户删除成功')
      fetchUsers()
    } catch (error: any) {
      if (error.response && error.response.status === 403) {
        ElMessage.error('权限不足，请重新登录')
        // 清除本地存储并跳转到登录页
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
        router.push('/login')
      } else {
        ElMessage.error('用户删除失败')
      }
    }
  }).catch(() => {
    // 取消删除
  })
}

// 获取角色列表
const fetchRoles = async () => {
  try {
    const response = await request.get('/api/roles')
    roles.value = response.data.map(role => ({
      id: role.id,
      roleName: role.roleName,
      roleDescription: role.roleDescription
    }))
  } catch (error) {
    ElMessage.error('获取角色列表失败')
  }
}

// 根据角色名称获取角色描述
const getRoleDescription = (roleName: string) => {
  const role = roles.value.find(r => r.roleName === roleName)
  return role ? (role.roleDescription || role.roleName) : roleName
}

// 组件挂载时获取用户列表和角色列表
onMounted(() => {
  fetchUsers()
  fetchRoles()
})
</script>

<style scoped>
.user-management {
  padding: 0;
  background-color: #f5f7fa;
  min-height: 100%;
  width: 100%;
  height: 100%;
}

.header {
  margin-bottom: 20px;
}

.header h2 {
  color: #303133;
  margin-bottom: 5px;
}

.header p {
  color: #606266;
  margin: 0;
}

.toolbar {
  margin-bottom: 20px;
}

.search-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 0;
}

.search-fields {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.user-table {
  margin-bottom: 0;
}

.user-table :deep(.el-card) {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.user-table :deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.user-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  object-fit: cover;
}

:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  border-radius: 8px 8px 0 0;
}
</style>